var glob = require('glob')
var path = require('path')
var fs = require('fs')

var changeFileMap = {}
var fileList = glob.sync('./src/?(pages|components)/**/*.vue')

fileList.forEach(function (file) {
  // console.log('111', path.resolve(file))
  let content = fs.readFileSync(file, 'utf-8')
  let isReplace

  // console.log('content', content)
  content = content.replace(/<style(.|\n|\r)*style>/gim, (cssContent) => {
    const [isBgReplace, newBgContent] = replaceBg(cssContent)

    if (isBgReplace) {
      isReplace = true
    }

    const [isFontReplace, newFontContent] = replaceFont(newBgContent)

    if (isFontReplace) {
      isReplace = true
    }

    return newFontContent
  })

  if (isReplace) {
    changeFileMap[file] = content
  }
})

Object.keys(changeFileMap).forEach((file) => {
  fs.writeFileSync(file, changeFileMap[file])
})

console.log('本次共扫码', fileList.length, '个文件')
console.log('处理', Object.keys(changeFileMap).length, '个文件')

function hex(x) {
  return ('0' + parseInt(x).toString(16)).slice(-2)
}

function replaceCssVal(colorMap, cssVal) {
  let isReplace = false

  cssVal = cssVal
    .replace(/rgb\(\s*([^)]+)\s*\)/g, ($0, $1) => {
      var reg = /(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})/
      var arr = reg.exec($1)
      return '#' + hex(arr[1]) + hex(arr[2]) + hex(arr[3])
    })
    .replace(/rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3}),\s*([^)]+)\s*\)/gi, ($0, r, g, b, a) => {
      return `rgba(#${hex(r)}${hex(g)}${hex(b)}, ${a})`
    })
    .replace(/#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})/g, ($0) => {
      const newVal = colorMap[$0]

      if (newVal) {
        isReplace = true

        return newVal
      }

      return $0
    })

  return {
    isReplace,
    cssVal,
  }
}
function replaceBg(content) {
  var colorMap = {
    '#ffffff': '$--bg-content-c',
    '#fff': '$--bg-content-c',
    '#f5f5f5': '$--bg-body-c',
    '#f9f9f9': '$--bg-title-c',
  }
  var isReplace

  content = content
    .replace(/( background-color:)([^;]+);/gi, ($0, $1, $2) => {
      const { isReplace: isBgReplace, cssVal } = replaceCssVal(colorMap, $2)

      if (isBgReplace) {
        isReplace = true
      }

      return $1 + cssVal + ';'
    })
    .replace(/( background:)([^;]+);/gi, ($0, $1, $2) => {
      const { isReplace: isBgReplace, cssVal } = replaceCssVal(colorMap, $2)

      if (isBgReplace) {
        isReplace = true
      }

      return $1 + cssVal + ';'
    })

  return [isReplace, content]
}

function replaceFont(content) {
  var colorMap = {
    '#262626': '$--font-primary-c',
    '#666666': '$--font-regular-c',
    '#666': '$--font-regular-c',
    '#999999': '$--font-secondary-c',
    '#999': '$--font-secondary-c',
  }
  var isReplace

  content = content.replace(/( color:)([^;]+);/gi, ($0, $1, $2) => {
    const { isReplace: isColorReplace, cssVal } = replaceCssVal(colorMap, $2)

    if (isColorReplace) {
      isReplace = true
    }

    return $1 + cssVal + ';'
  })

  return [isReplace, content]
}
